package laxoffice

/**
普通文件处理
 */

import (
	"bufio"
	"io"
	"os"
)

// @Desc: 文件的每一行回调
// @param filePathAndName
// @param startLineNum
// @param rowCallBack
// @return error
func FileEachRow(filePathAndName string, startLineNum int, rowCallBack func(fileIndex int, fileRow string) error)  error {
	fs, err := os.Open(filePathAndName)
	if err != nil {
		return err
	}
	defer fs.Close()
	if rowCallBack == nil {
		return nil
	}
	r := bufio.NewReader(fs)
	var idx = 0
	for {
		row, _, err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		idx++
		if idx < startLineNum {
			continue
		}
		if err = rowCallBack(idx, string(row)); err != nil {
			return err
		}
	}
	return nil
}

// @Desc: 写普通文件
type LaxFileWriter struct {
	*bufio.Writer
	f *os.File
}

// @Desc: 创建一个writer
// @param filePathAndName
// @return *LaxFileWriter
// @return error
func NewLaxNormalFileWriter(filePathAndName string) (*LaxFileWriter, error) {
	fs, err := os.OpenFile(filePathAndName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		return nil, err
	}
	w := bufio.NewWriter(fs)
	return &LaxFileWriter{
		Writer: w,
		f:      fs,
	}, nil
}

func (lfw *LaxFileWriter) Finish() {
	if lfw.Writer != nil {
		lfw.Flush()
		lfw.Writer = nil
	}
	if lfw.f != nil {
		lfw.f.Close()
		lfw.f = nil
	}
}